#!/usr/bin/env python
# @Author  : Bright (brt2@qq.com)
# @Create  : 2024-03-23
# @Update  : 2024-03-23 / 0.1.0

import time
import logzero
from atexit import register
# import inspect

def elapsed(func, output_func=print):
    """ Function decorator
        output_func: 可以是log操作
    """
    def running(*args, **kwarg):
        time_0 = time.time()
        # str_0 = f"起始时刻：{ctime.time()}"
        res = func(*args, **kwarg)
        time_1 = time.time()
        # str_1 = f"结束时刻：{ctime.time()}"

        consuming = time_1 - time_0
        # curr_func_name = inspect.currentframe().f_code.co_name
        output_func(f"【{func.__qualname__}】耗时统计：{consuming:0.3f}")
        return res
    return running


class StaticTimeLogger:
    def __init__(self, path_log):
        register(self.del_func)
        import os.path

        fname = os.path.basename(path_log)
        # logzero.logfile(fname, disableStderrLogger=True)
        self.logger = logzero.setup_logger(name=fname, logfile=path_log, level=logzero.DEBUG)
        self.straight_records: list[tuple[float, str]] = []  # time.time(), "注释"
        self.couples_records: dict[str, float] = {}

    # def __del__(self):
        # 实际上，这里运行报错: 不允许open调用

    def del_func(self):
        if self.straight_records:
            self.print_times()

    def record_curr_time(self, comment=None):
        """ record_straight """
        self.straight_records.append((time.time(), comment))

    record = record_curr_time

    def record_tag(self, comment):
        """ new couple """
        assert comment not in self.couples_records
        self.couples_records[comment] = time.time()

    def record_match(self, comment):
        """ match the couple """
        time_diff = time.time() - self.couples_records[comment]
        del self.couples_records[comment]
        self.logger.debug(time_diff)

    @elapsed
    def print_times(self):
        # print(">>>", self.straight_records)
        first_escaped = self.straight_records[0]
        record_diff = "耗时统计"
        for i in range(len(self.straight_records)-1):
            time_diff = self.straight_records[i+1][0] - self.straight_records[i][0]
            record_diff += f"\ndt_{i}\t= {time_diff:0.3f}"
            if self.straight_records[i+1][1]:
                record_diff += " \t # " + self.straight_records[i+1][1]

        self.logger.debug(record_diff)
        # reset self.straight_records
        self.straight_records.clear()
        return first_escaped


if __name__ == "__main__":
    logger = StaticTimeLogger("./log-merge.log")
    logger.record()

    for i in range(3):
        time.sleep(0.15)
        logger.record(f"time_{i}")

    # logger.print_times()
